package org.bt4girls.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bt4girls.common.constant.CommonConstant;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class JwtUtils {
    private static final Map<String, Object> JWT_HEADER = new HashMap<>(2);

    static {
        JWT_HEADER.put("Type", "Jwt");
        JWT_HEADER.put("alg", "HS256");
    }

    /***
     * 生成jwt字符串
     * @param uid 用户ID
     * @param username 用户名
     * @return String JWT
     */
    public static String generateUserJwt(Long uid, String username) {
        Algorithm algorithm = Algorithm.HMAC256(CommonConstant.JWT_KEY);
        return JWT.create()
                .withClaim("uid", String.valueOf(uid))
                .withClaim("username", username)
                .withHeader(JWT_HEADER)
                .withExpiresAt(new Date(System.currentTimeMillis() + CommonConstant.JWT_ACCESS_TOKEN_EXPIRES_MS))
                .sign(algorithm);
    }

    /***
     * 验证JWT是否正确/过期
     * @param jwt 原字符串
     * @return 是否正确
     */
    public static boolean verifyJwt(String jwt) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(CommonConstant.JWT_KEY);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(jwt);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /***
     * 生成刷新token的长度
     * @return token
     */
    public static String generateRefreshToken() {
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
